<?php
/**
 * @file
 *  Defines functions and interface for the configuration interface of the ldap_map module.
 */

/**
 * Callback for the configuration menu item.
 */
function ldap_map_configure() {
    return drupal_get_form('ldap_map_form');
}

/**
 * Implements hook_form().
 */
function ldap_map_form($form, &$form_state) {
    $css = drupal_get_path('module', 'ldap_map') . '/ldap_map.admin.css';
    drupal_add_css($css, 'file');

    $fields = _ldap_map_get_field_names();
    $servers = array_merge(array(NULL => NULL), _ldap_map_get_server_names());
    $values = _ldap_map_get_values();

    //Build the form.
    $form = array();

    //Attribute lookup tool
    $form['attributes'] = array(
        '#tree' => TRUE,
        '#type' => 'fieldset',
        '#title' => t('Attribute Lookup'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );

    $form['attributes']['helptext'] = array(
        '#type' => 'markup',
        '#prefix' => '<div>',
        '#markup' => t('Use this tool to look up a user in the LDAP and see which attributes are available to you.'),
        '#suffix' => '</div>',
    );

    $form['attributes']['server'] = array(
        '#type' => 'select',
        '#title' => t('Server'),
        '#description' => t('Choose an LDAP server to draw data from.'),
        '#options' => _ldap_map_get_server_names(),
        '#prefix' => '<div>',
    );

    $form['attributes']['username'] = array(
        '#type' => 'textfield',
        '#title' => t('User name'),
        '#description' => t('Enter a user name to use for the search'),
        '#size' => 25,
        '#suffix' => '</div>',
    );

    $form['attributes']['button'] = array(
        '#type' => 'submit',
        '#value' => t('Run'),
    );

    //Field config.
    $form['fields'] = array(
        '#tree' => TRUE,
    );

    foreach ($fields as $fid => $field) {
        $defaults = array('server' => NULL, 'value' => NULL);
        if (isset($values[$field])) {
            $defaults = $values[$field];
        }

        $form['fields'][$field] = array(
            '#tree' => TRUE,
            '#type' => 'fieldset',
            '#title' => check_plain($field),
            '#collapsible' => TRUE,
            '#collapsed' => TRUE,
        );

        $form['fields'][$field]['fid'] = array(
            '#type' => 'hidden',
            '#value' => $fid,
        );

        $form['fields'][$field]['server'] = array(
            '#type' => 'select',
            '#title' => t('Server'),
            '#description' => t('Choose a LDAP server to draw data from.'),
            '#options' => $servers,
            '#default_value' => $defaults['server'],
        );

        $form['fields'][$field]['value'] = array(
            '#title' => 'Value',
            '#type' => 'textfield',
            '#size' =>  60,
            '#default_value' => $defaults['value'],
        );

    }

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save'),
    );

    return $form;
}

/**
 * Submit handler for the administration form.
 */
function ldap_map_form_submit(&$form, &$form_state) {

    if ($form_state['clicked_button']['#value'] == 'Run') {
            $server = $form_state['values']['attributes']['server'];
            $username = $form_state['values']['attributes']['username'];
            //$account = array('name' => $form_state['values']['attributes']['username']);
            //$ldap_data = ldap_servers_get_user_ldap_data((object)$account);

            $ldap_data = _ldap_map_user_lookup($server, $username);

            $message = print_r($ldap_data, TRUE);
            drupal_set_message(check_markup($message));
    }
    else {
        $result = _ldap_map_save($form_state);
        if ($result) {
            drupal_set_message(t('Settings saved.'));
        }
        else {
            drupal_set_message(t('Error, couldn\'t save the settings.'));
        }
    }

}

/**
 * Perorm a lookup on a user against an LDAP server
 *
 * @param $sid
 *  The machine name of the server to query.
 *
 * @param $username
 *  The username of the user to perform the lookup on.
 *
 * @return
 *  An array containing the user's LDAP data.
 */
function _ldap_map_user_lookup($sid, $username) {

    $servers = ldap_servers_get_servers(NULL, 'enabled');

    $servers[$sid]->connect();
    $value = $servers[$sid]->user_lookup($username);
    $servers[$sid]->disconnect();

    return $value;
}

/**
 * Get ldap server names.
 *
 * @return
 *  Returns an array of server names, indexed by the server id.
 */
function _ldap_map_get_server_names() {
    //Find the servers that are endabled.
    $servers = ldap_servers_get_servers(NULL, 'enabled');

    $server_names = array();
    foreach ($servers as $server) {
        $server_names[$server->sid] = $server->name;
    }

    unset($servers);

    return $server_names;

}

/**
 * Get the profile fields..
 *
 * @return
 *  Returns an array of profile fields, indexed by the field id.
 */
function _ldap_map_get_field_names() {
    //First, find the fields that belong to the user.
    $query = db_select('field_config_instance', 'fci');
    $query->condition('fci.bundle', 'user');
    $query->fields('fci', array('field_id', 'field_name'));
    $results = $query->execute();

    $fields = array();
    foreach ($results as $result) {
        $fields[$result->field_id] = $result->field_name;
    }

    unset($results);

    return $fields;
}

/**
 * Get ldap server names.
 *
 * @param $form_state
 *  The form state.
 *
 * @return
 *  Returns an array of server names, indexed by the server id.
 */
function _ldap_map_save($form_state) {

    if (!isset($form_state['values']['fields'])) {
        return FALSE;
    }

    foreach ($form_state['values']['fields'] as $field_name => $field) {
        if ($field['server'] != NULL) {
            $record = array(
                'field_id' => $field['fid'],
                'field_name' => $field_name,
                'server_name' => $field['server'],
                'ldap_attribute' => $field['value'],
            );

            if ($field['value'] != '') {
                db_merge('ldap_map')
                ->key(array('field_id' => $record['field_id']))
                ->fields($record)
                ->execute();
            }
        }
    }
    return TRUE;
}
